<template>
  <el-dialog
    class="modify-class"
    width="90%"
    :title="title"
    visible
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <el-form :model="formData" class="form" label-width="120px">
      <el-form-item label="任务名称" prop="modelName">
        <el-input
          class="input"
          v-model="formData.modelName"
          placeholder="101011型号01批/综合控制系统"
          style="width: 600px;"
        />
      </el-form-item>
      <el-form-item label="任务简介" prop="modelDescribe">
        <el-input
          class="desc-input"
          type="textarea"
          v-model="formData.modelDescribe"
          :rows="3"
          placeholder="请输入型号项目相关描述……"
        />
      </el-form-item>
      <div style="position: relative;">
        <el-tabs v-model="curTab">
          <el-tab-pane label="基本配套信息" name="1">
            <c-table
              ref="deviceRef"
              key="device"
              :table-data="formData.detailList"
              :table-column="tableColumn"
              :height="300"
              @input-change="inputChangeHandle"
              @on-save="onSave"
              @on-delete="onDelete"
            ></c-table>
          </el-tab-pane>
          <el-tab-pane label="系统配套信息" name="2">
            <c-table
              ref="sysRef"
              key="sys"
              :table-data="formData.sysMatchList"
              :table-column="tableColumn2"
              :height="300"
              @on-save="onSave"
              @on-delete="onDelete"
            ></c-table>
          </el-tab-pane>
        </el-tabs>

        <el-button
          class="btn-add"
          icon="el-icon-plus"
          @click="addHandle"
          style="position: absolute; top: 0; right: 0; z-index: 2;"
        ></el-button>
      </div>
    </el-form>
    <div class="dialog-footer" slot="footer">
      <el-button class="btn-comfirm" type="primary" @click="saveHandle">确认</el-button>
      <el-button class="btn-cancel" @click="cancelHandle">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { overviewApis } from '@/apis'
import Schema from 'async-validator';

const descriptor = {
  sysCode: { required: true },
  sysName: { required: true },
  deviceCode: { required: true },
  deviceName: { required: true },
  deviceNum: {required: true },
  classify: { required: true },
  formalNum: { required: true },
  testNum: { required: true },
  matchOrg: { required: true },
  designOrg: { required: true },
  productionOrg: { required: true },
}

// 系统信息验证
const sysDescriptor = {
  sysCode: { required: true },
  sysName: { required: true },
  matchNum: { required: true},
}

// 验证器
const validator = new Schema(descriptor);

const systemValidator = new Schema(sysDescriptor)

const validatePromise = function(row) {
  return new Promise((resolve, reject) => {
  validator.validate(row, (err) => {
      if (err) {
        return reject(err)
      }
      resolve()
    })
  })
}

const sysValidatePromise = function(row) {
  return new Promise((resolve, reject) => {
  systemValidator.validate(row, (err) => {
      if (err) {
        return reject(err)
      }
      resolve()
    })
  })
}

export default {
  props: {
    editData: {
      type: Object,
      default() {
        return null;
      },
    },
  },
  data() {
    return {
      loading: false,
      formData: {
        modelName: "",
        modelDescribe: "",
        detailList: [
          // {
          //   edit: false,
          //   designOrg: "hp",
          //   deviceCode: "pc",
          //   deviceName: "电脑",
          //   deviceNum: 5,
          //   productionOrg: "开发公司",
          //   sysCode: "AAA",
          //   sysName: "监控系统",
          //   sysSubCode: "AAA-a",
          //   sysSubName: "综合子系统",
          // },
        ],
        deleteList: [],
        // 系统信息
        sysMatchList: [],
        sysDeleteList: [],
      },
      curTab: "1",
      tableColumn: {
        sysCode: {
          type: 'input',
          label: "系统代号"
        },
        sysName: {
          type: 'input',
          label: "系统名称"
        },
        sysSubCode: {
          type: 'input',
          label: "分系统代号"
        },
        sysSubName: {
          type: 'input',
          label: "分系统名称"
        },
        deviceCode: {
          type: 'input',
          label: "单机代号"
        },
        deviceName: {
          type: 'input',
          label: "单机名称"
        },
        deviceNum: {
          // type: 'input',
          label: "单机数量"
        },
        classify: {
          type: 'input',
          label: '分类'
        },
        formalNum: {
          type: 'input',
          label: '正式订货数量',
          columnProp: {
            minWidth: 100
          }
        },
        testNum: {
          type: 'input',
          label: '测试订货数量',
          columnProp: {
            minWidth: 100
          }
        },
        matchOrg: {
          type: 'input',
          label: '齐套单位'
        },
        designOrg: {
          type: 'input',
          label: "设计单位"
        },
        productionOrg: {
          type: 'input',
          label: "生产单位"
        },
      },
      tableColumn2: {
        sysCode: {
          type: 'input',
          label: "系统代号"
        },
        sysName: {
          type: 'input',
          label: "系统名称"
        },
        sysSubCode: {
          type: 'input',
          label: "分系统代号"
        },
        sysSubName: {
          type: 'input',
          label: "分系统名称"
        },
        matchNum: {
          type: 'input',
          label: '配套数量'
        }
      }
    };
  },
  computed: {
    title() {
      return this.editData ? "编辑" : "新增";
    },
  },
  watch: {
    curTab() {
      this.updateLayout();
    }
  },
  methods: {
    inputChangeHandle(row, key) {
      console.log('input change key')
      if (key == 'formalNum' || key == 'testNum') {
        let {formalNum, testNum} = row;
        if (formalNum && testNum) {
          row.deviceNum = parseInt(formalNum) + parseInt(testNum);
        } else {
          row.deviceNum = formalNum || testNum
        }
      }
    },
    updateLayout() {
      this.$nextTick(() => {
        if (this.curTab == '1') {
          if (this.$refs.deviceRef) {
            this.$refs.deviceRef.$refs.multipleTable.doLayout();
          }
        } else {
          if (this.$refs.sysRef) {
            this.$refs.sysRef.$refs.multipleTable.doLayout();
          }
        }
      });
    },
    //保存
    onSave(row, index) {
      if (this.curTab == '1') {
        validator.validate(row, (err) => {
          if (!err) {
            this.formData.detailList[index].edit = false
          } else {
            this.$message.warning('数据不完整')
          }
        })
      } else {
        systemValidator.validate(row, (err) => {
          if (!err) {
            this.formData.sysMatchList[index].edit = false
          } else {
            this.$message.warning('数据不完整')
          }
        })
      }
    },
    //删除
    onDelete(row, index) {
      let list = this.formData.detailList, deleteList = this.formData.deleteList;
      if (this.curTab == '2') {
        list = this.formData.sysMatchList;
        deleteList = this.formData.sysDeleteList;
      }
      if (row.id) {
        deleteList.push(row.id)
      }
      list.splice(index, 1)
      this.updateLayout()
    },
    close(refresh) {
      this.$emit("close", refresh);
    },
    beforeClose() {
      this.close(false);
    },
    requestDetail(params) {
      this.loading = true
      overviewApis.findByModelId(params).then(({data}) => {
        this.formData.id = data.id
        this.formData.modelName = data.modelName
        this.formData.modelDescribe = data.modelDescribe
        this.formData.detailList = (data.detailList || []).map(item => {
          item.edit = false
          return item
        })
        this.formData.sysMatchList = (data.sysMatchList || []).map(item => {
          item.edit = false
          return item
        })
        this.updateLayout();
      }).then(() => {
        this.loading = false
      })
    },
    addHandle() {
      if (this.curTab == '1') {
        this.formData.detailList.push({
          designOrg: "",
          deviceCode: "",
          deviceName: "",
          deviceNum: "",
          edit: true,
          productionOrg: "",
          sysCode: "",
          sysName: "",
          classify: "",
          formalNum: "",
          testNum: "",
          matchOrg: "",
          sysSubCode: "",
          sysSubName: "",
        });
      } else {
        this.formData.sysMatchList.push({
          sysCode: "",
          sysName: "",
          sysSubCode: "",
          sysSubName: "",
          matchNum: "",
          edit: true,
        })
      }
      this.updateLayout()
    },
    cancelHandle() {
      this.close(false);
    },
    async saveHandle() {
      let {id, modelName, modelDescribe, detailList, deleteList, sysMatchList, sysDeleteList} = this.formData
      let formData = {
        id,
        modelName,
        modelDescribe,
        deleteList,
        insertList:[],
        updateList:[],
        sysDeleteList,
        sysInsertList: [],
        sysUpdateList: [],
      }
      for(let index = 0; index < detailList.length; index++) {
        let item = detailList[index];
        try {
          await validatePromise(item);
        } catch(err) {
          return this.$message.warning('基本配套信息数据不完整')
        }

        if (item.id) {
          formData.updateList.push({...item})
        } else {
          formData.insertList.push({...item})
        }
      }

      for(let index = 0; index < sysMatchList.length; index++) {
        let item = sysMatchList[index];
        try {
          await sysValidatePromise(item);
        } catch(err) {
          return this.$message.warning('系统配套信息数据不完整')
        }

        if (item.id) {
          formData.sysUpdateList.push({...item})
        } else {
          formData.sysInsertList.push({...item})
        }
      }

      this.$emit("model-save", formData);
    },
  },
  mounted() {
    if (this.editData) {
      this.requestDetail({modelId: this.editData.modelId})
    } else {
     // this.addHandle();
    }
  },
};
</script>

<style lang="scss" scoped>
</style>